package com.cloudsigns.factorymanager2.project.customview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import com.cloudsigns.factorymanager2.project.bean.DiskBean;

import java.util.List;

/**
 * Created by tony on 2017/11/25.
 */

public class DiskView extends View {
    private DiskBean[] datas;
    private int[] colors = {0xff000000, 0xffffffff};
    private Paint textPaint;
    private Paint mArcPaint;
    /**
     * 圆形背景的画笔
     **/
    private Paint mBackColorPaint;
    /**
     * 绘制分割线的画笔
     */
    private Paint mLinePaint;


    private RectF rectF;
    private int w;          //View宽高
    private int h;

    float sweepAngle;  //扇形扫过的角度
    /**
     * 控件的中心位置
     */
    private int mCenter;


    /**
     * 触摸点的坐标位置
     **/
    private float touchX;
    private float touchY;
    /**
     * 500毫秒内的点击被认为是点击事件
     **/
    private long timeClick = 500;

    /**
     * 保存点击的时间
     **/
    private long nowClick;

    /**
     * 被选中的position,默认第0个选中
     **/
    private int defaultPosition = 0;


    /**
     * 内圈画盘小圆的宽度，这边是在1080p下的730，绘画区域
     **/
    private float mRangeWidth = 730;

    public DiskView(Context context) {
        super(context);
        initPaint();
    }

    public DiskView(Context context, AttributeSet attrs) {
        super(context, attrs);

    }

    public DiskView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }


    public void setDatas(DiskBean[] datas, int defaultPosition) {
        this.datas = datas;
        this.defaultPosition = defaultPosition;
        invalidate();
    }

    private void initPaint() {

        // 初始化绘制圆弧的画笔
        mArcPaint = new Paint();
        mArcPaint.setAntiAlias(true);
        mArcPaint.setDither(true);
        // 初始化绘制文字的画笔
        textPaint = new Paint();
        textPaint.setColor(0xff222222);
        textPaint.setTextAlign(Paint.Align.CENTER);
        textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
        textPaint.setTextSize(30);
        textPaint.setAntiAlias(true);
        textPaint.setDither(true);
        //圆形背景的画笔
        mBackColorPaint = new Paint();
        mBackColorPaint.setColor(0xffae6112);
        mBackColorPaint.setAntiAlias(true);
        mBackColorPaint.setDither(true);
        //未选中的分割线的画笔
        mLinePaint = new Paint();
        mLinePaint.setAntiAlias(true);
        mLinePaint.setDither(true);
        mLinePaint.setStrokeWidth(3);
        mLinePaint.setStyle(Paint.Style.FILL);
        mLinePaint.setColor(0xffFCFCFC);


        //初始化区域
        rectF = new RectF();

        if (datas != null && datas.length > 0) {
            sweepAngle = (float) (360 / datas.length);
        }


    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        this.w = w;     //获取宽高
        this.h = h;
        // 中心点
        mCenter = w / 2;
    }

    /**
     * 设置控件为正方形
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = Math.min(getMeasuredWidth(), getMeasuredHeight());
        // 中心点
        mCenter = width / 2;
        this.w = width;
        //屏幕的宽度
        setMeasuredDimension(width, width);
        initPaint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (datas != null && datas.length > 0) {
            canvas.translate(w / 2, h / 2);             //将画布坐标原点移到中心位置
            float currentStartAngle = 0;                //起始角度
            float r = (float) (Math.min(w, h) / 2);     //饼状图半径(取宽高里最小的值)
            rectF.set(-r, -r, r, r);                    //设置将要用来画扇形的矩形的轮廓
            for (int i = 0; i < datas.length; i++) {
                DiskBean diskBean = datas[i];


                if (diskBean.status == 1) {
                    mArcPaint.setColor(0xff4BAEE3);
                    textPaint.setColor(colors[1]);
                    mLinePaint.setColor(colors[1]);
                } else if (diskBean.status == 0) {
                    mArcPaint.setColor(0xffD6DCE5);
                    textPaint.setColor(colors[0]);
                    mLinePaint.setColor(colors[0]);
                }


                //绘制扇形(通过绘制圆弧)
                canvas.drawArc(rectF, currentStartAngle, sweepAngle, true, mArcPaint);


                //绘制扇形上文字
                float textAngle = currentStartAngle + sweepAngle / 2;    //计算文字位置角度

                float x = (float) (r / 2 * Math.cos(textAngle * Math.PI / 180));    //计算文字位置坐标
                float y = (float) (r / 2 * Math.sin(textAngle * Math.PI / 180));

                canvas.drawText(diskBean.text, x, y, textPaint);    //绘制文字

                //绘制分割线，这里保证没一个小块都有一条分割线，分割线的位置是在最右侧
                drawCanvasLine(canvas, r);


//                float imgWidth = r;
//                float bmpAngle = currentStartAngle + sweepAngle;
//                float bmpx = (float) (r  * Math.cos(textAngle * Math.PI / 180));    //计算图片位置坐标
//                float bmpy = (float) (r * Math.sin(textAngle * Math.PI / 180));
//
//                RectF rect = new RectF(bmpx - imgWidth / 2, bmpy - imgWidth / 2, bmpx + imgWidth
//                        / 2, bmpy + imgWidth / 2);
//                canvas.drawBitmap(diskBean.bitmap, null, rect, null);


//                // 设置图片的宽度为直径的1/8
//                float imgWidth = r / 8;
//
//                float angle = (float) ((30 + currentStartAngle) * (Math.PI / 180));
//
//                float bmpx = (int) (mCenter + r / 2 / 2 * Math.cos(angle));
//                float bmpy = (int) (mCenter + r / 2 / 2 * Math.sin(angle));
//
//                // 确定绘制图片的位置
//                RectF rect = new RectF(bmpx - imgWidth / 2, bmpy - imgWidth / 2, bmpx + imgWidth
//                        / 2, bmpy + imgWidth / 2);
//
//                canvas.drawBitmap(diskBean.bitmap, null, rect, null);


                currentStartAngle += sweepAngle;     //改变起始角度
            }
        }

    }


    /**
     * 绘制分割线
     **/
    private void drawCanvasLine(Canvas canvas, float radio) {
        int mItemCount = 6;
        //计算终点角度，这边从最上边为0度开始计算,则角度在0-180之间，给0.5f的偏移
        float range = 360f / mItemCount / 2 - 0.5f;
//        //计算半径的长度
//        float radio = (rectF.right - rectF.left) / 2;
        //计算终点坐标
        float x = 0;
        float y = 0;
        if (range < 90) {
            x = (float) (radio * Math.sin(Math.toRadians(range)));
            y = (float) (radio * Math.cos(Math.toRadians(range)));

            x += mCenter;
            y = mCenter - y;
        } else {
            x = (float) (radio * Math.sin(Math.toRadians(180 - range)));
            y = (float) (radio * Math.cos(Math.toRadians(180 - range)));

            x += mCenter;
            y += mCenter;
        }


        canvas.drawLine(mCenter, mCenter, x, y, mLinePaint);
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
//        float ex = event.getX();
//        float ey = event.getY();
//        //判断按点是否在圆内
//        if (!rectF.contains(event.getX(), event.getY())) {
//            return true;
//        }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchX = event.getX();
                touchY = event.getY();
                //按下时的时间
                nowClick = System.currentTimeMillis();
                break;
            case MotionEvent.ACTION_MOVE:
                float moveX = event.getX();
                float moveY = event.getY();

                //重新赋值
                touchX = moveX;
                touchY = moveY;

                break;
            case MotionEvent.ACTION_UP:
                if (System.currentTimeMillis() - nowClick <= timeClick) {//此时为点击事件
                    //落点的角度加上偏移量基于初始的点的位置
                   int  checkPosition = calInExactArea(getRoundArc(event.getX(), event.getY()));
                    if (mOnWheelCheckListener != null) {
                        mOnWheelCheckListener.onCheck(checkPosition);
                    }
                }
                break;
        }
        return true;
    }

    //根据落点计算角度
    private float getRoundArc(float upX, float upY) {
        float arc = 0;
        //首先计算三边的长度
        float a = (float) Math.sqrt(Math.pow(mCenter - mCenter, 2) + Math.pow(0 - mCenter, 2));
        float b = (float) Math.sqrt(Math.pow(upX - mCenter, 2) + Math.pow(upY - mCenter, 2));
        float c = (float) Math.sqrt(Math.pow(upX - mCenter, 2) + Math.pow(upY - 0, 2));
        //判断是否为三角形
        if (a + b > c) {//两边之和大于第三边为三角形
            /**
             * 接下来计算角度
             *
             * acos((a2+b2-c2)/2ab)
             *
             * **/
            arc = (float) (Math.acos((Math.pow(a, 2) + Math.pow(b, 2) - Math.pow(c, 2)) / (2 * a * b)) * 180 / Math.PI);

            //判断是大于左边还是右边，也就是180以内还是以外
            if (upX < mCenter) {//此时是180以外的
                arc = 360 - arc;
            }
        } else {//上下边界的问题
            if (upX == mCenter) {
                if (upY < mCenter) {
                    arc = 0;
                } else {
                    arc = 180;
                }
            }
        }
        return arc;
    }

    /**
     * 根据当前旋转的mStartAngle计算当前滚动到的区域
     *
     * @param startAngle
     */
    public int calInExactArea(float startAngle) {
        float size = 360f / 6;
        // 确保rotate是正的，且在0-360度之间
        float rotate = (startAngle % 360.0f + 360.0f) % 360.0f;

        for (int i = 0; i < 6; i++) {
            // 每个的中奖范围
            if (i == 0) {
                if ((rotate > 360 - size / 2) || (rotate < size / 2)) {
                    return i;
                }
            } else {
                float from = size * (i - 1) + size / 2;
                float to = from + size;
                if ((rotate > from) && (rotate < to)) {
                    return i;
                }
            }
        }
        return -1;
    }


    private OnWheelCheckListener mOnWheelCheckListener;

    public void setOnWheelCheckListener(OnWheelCheckListener mOnWheelCheckListener) {
        this.mOnWheelCheckListener = mOnWheelCheckListener;
    }

    public static interface OnWheelCheckListener {
        void onCheck(int position);
    }

    public int getDefaultPosition() {
        return defaultPosition;
    }
}

